
#include "GraphicFactory.h"
#include "GraphicFactoryD3D.h"
#include "GraphicFactoryOGL.h"

namespace Graphics
{
	GraphicFactory::GraphicFactory()
	{}

	API_TYPE GraphicFactory::m_API = API_UNDEF;

	GraphicFactory* GraphicFactory::m_GF = 0;

	void GraphicFactory::init(std::pair<API_TYPE,Window> param)
	{
		API_TYPE api=param.first;
		Window& win=param.second;

		m_API = api;

		switch(m_API)
		{
		case API_D3D9:
			m_GF=new D3Ds::GraphicFactoryD3D(win);
			break;

		case API_OPENGL:
			m_GF=new OGLs::GraphicFactoryOGL(win);
			break;

		default:
			m_API = API_UNDEF;
			m_GF = 0;
			throw(std::exception("Unknow API type"));
		}
	}

	GraphicFactory* GraphicFactory::getInstance()
	{
		return m_GF;
	}

	GraphicFactory::~GraphicFactory(void)
	{
		for(stdext::hash_map<string,Drawable*>::iterator i=m_Cache.begin();i!=m_Cache.end();i++)
		{
			if(i->second )
			{
				delete i->second;
				i->second = 0;
			}
		}
		
	}

	API_TYPE& GraphicFactory::GetAPI(void)
	{
		return m_API;
	}

	
	Drawable* GraphicFactory::GetDrawableFromCache(const std::string& filename,DWORD colorKey)
	{
		std::string key =filename;
		char str[10];
		str[0] = '|';
		_itoa_s((int)colorKey,str+1,9,16);
		key.append(str);
		
		Drawable* dd = m_Cache[key];

		if( dd == 0)
		{
			try
			{
				dd = this->CreateDrawable(filename,colorKey);
				m_Cache[key] = dd;
			}
			catch(...)
			{
				dd = 0;
			}
		}

		return dd;
	}
	
}